
import 'package:flutter/material.dart';

import '../base/christmas_light_style.dart';

const double _kLinearProgressIndicatorHeight = 6.0;
const int _kIndeterminateLinearDuration = 1800;

/// 渐变进度条
class ChristmasLightProgressBar extends StatefulWidget {
  final double? value;
  final double? minHeight;
  final LinearGradient gradient;

  const ChristmasLightProgressBar({
    Key? key,
    this.value,
    this.minHeight,
    this.gradient = const LinearGradient(
      begin: Alignment.centerLeft,
      end: Alignment.centerRight,
      colors: const [Color(0xFF4136f1), Color(0xFF8643ff)],
    ),
  }) : super(key: key);

  @override
  State<ChristmasLightProgressBar> createState() =>
      _ChristmasLightProgressBarState();
}

class _ChristmasLightProgressBarState extends State<ChristmasLightProgressBar>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> pAnimation;
  List<Color> colors = [];

  double? prevValue = 0.0;

  late CurvedAnimation curvedAnimation;

  @override
  void initState() {
    super.initState();
    assert(widget.gradient.colors.length == 2,
        'gradient must have two colors only');

    _setColorsArray();

    _controller = AnimationController(
      duration: const Duration(milliseconds: _kIndeterminateLinearDuration),
      vsync: this,
    );

    _setControllerListener();

    curvedAnimation = CurvedAnimation(
      parent: _controller,
      curve: Curves.fastOutSlowIn,
    );

    pAnimation = Tween<double>(begin: prevValue, end: widget.value ?? 1.0)
        .animate(curvedAnimation);
    prevValue = widget.value ?? 0.0;

    _controller.forward();
  }

  void _setColorsArray() {
    colors.clear();
    colors.addAll(widget.gradient.colors);
    // colors.add(widget.gradient.colors.first);
    colors.add(christmasLightStyle.progressBackgroundColor);
  }

  void _setControllerListener() {
    if (widget.value == null) {
      _controller.addStatusListener((status) {
        if (status == AnimationStatus.dismissed && widget.value == null) {
          _controller.forward();
        } else if (status == AnimationStatus.completed &&
            widget.value == null) {
          _controller.reverse();
        }
      });
    }
  }

  @override
  void didUpdateWidget(ChristmasLightProgressBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    _setColorsArray();
    _setControllerListener();
    if (widget.value == null && !_controller.isAnimating) {
      _controller.reset();
    } else if (widget.value != null) {
      pAnimation = Tween<double>(begin: prevValue, end: widget.value)
          .animate(curvedAnimation);
      _controller
        ..reset()
        ..forward();
      prevValue = widget.value;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void stopAnimation() {
    _controller.stop();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: pAnimation,
      builder: (_, __) {
        return Container(
          constraints: BoxConstraints.tightFor(
            width: double.infinity,
            height: widget.minHeight ?? _kLinearProgressIndicatorHeight,
          ),
          decoration: BoxDecoration(
            color: christmasLightStyle.progressBackgroundColor,
            borderRadius: BorderRadius.circular(5.0),
            gradient: LinearGradient(
              begin: widget.gradient.begin,
              end: widget.gradient.end,
              stops: <double>[
                0.0,
                pAnimation.value,
                widget.value == null ? 1.0 : pAnimation.value + 0.01,
              ],
              colors: colors,
            ),
          ),
        );
      },
    );
  }
}

/// 加载Loading
class ChristmasLightLoading extends StatelessWidget {
  final String? text;

  ChristmasLightLoading({Key? key, this.text}) : super(key: key);

  final String _loading = const AssetImage(
    'assets/images/icon_loading.gif',
  ).keyName;

  @override
  Widget build(BuildContext context) {
    return UnconstrainedBox(
      child: Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        insetPadding: EdgeInsets.zero,
        insetAnimationCurve: Curves.easeInOut,
        insetAnimationDuration: Duration(milliseconds: 100),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 35.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // CircularProgressIndicator(),
              Image.asset(_loading, width: 45, height: 45),
              if (text != null)
                Padding(
                  padding: const EdgeInsets.only(top: 15.0),
                  child: Text(text!),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
